package com.zhugang.week06;

import java.util.ArrayList;
import java.util.List;
import java.util.Stack;

/**
 * @program algorithms
 * @description: PreorderTraversal
 * @author: chanzhugang
 * @create: 2022/07/18 15:42
 */
public class PreorderTraversal3 {

    /**
     * 二叉树的前中后序遍历：非递归写法
     *
     * @param root
     * @return
     */
    List<Integer> result = new ArrayList<>();

    public List<Integer> preorderTraversal(TreeNode root) {
        // status表示每个节点出现在栈顶元素的次数（3次）
        /**
         * 1、左右子树均未遍历
         * 2、左子树遍历完，右子树未遍历
         * 3、左右子树都遍历完
         */
        if (root == null) {
            return result;
        }
        Stack<SFrame> stack = new Stack<>();
        stack.push(new SFrame(1, root));
        while (!stack.isEmpty()) {
            SFrame peek = stack.peek();
            if (peek.status == 1) {
                // 前序
                result.add(peek.node.val);
                peek.status = 2;
                if (peek.node.left != null) {
                    stack.push(new SFrame(1, peek.node.left));
                }
            }
            if (peek.status == 2) {
                // 中序
                // result.add(peek.node.val);
                peek.status = 3;
                if (peek.node.right != null) {
                    stack.push(new SFrame(1, peek.node.right));
                }
            }
            if (peek.status == 3) {
                // 后序
                // result.add(peek.node.val);
                stack.pop();
            }
        }
        return result;
    }

    public class SFrame {
        public int status;
        public TreeNode node = null;

        public SFrame(int status, TreeNode node) {
            this.status = status;
            this.node = node;
        }
    }

    public class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;

        TreeNode() {
        }

        TreeNode(int val) {
            this.val = val;
        }

        TreeNode(int val, TreeNode left, TreeNode right) {
            this.val = val;
            this.left = left;
            this.right = right;
        }
    }
}